//
//  TTMarketViewController.m
//  TaoTuo
//
//  Created by 周晨晔 on 2019/9/19.
//  Copyright © 2019 admin. All rights reserved.
//

#import "TTMarketViewController.h"
#import "TTMarketViewCell.h"
#import "TTMarketModel.h"

static NSString *cellID = @"market_cell_id";

@interface TTMarketViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UISwitch *mySwitch;

@end

@implementation TTMarketViewController

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"goldMarketListRefreshNotify" object:self.dataArray];
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        // 保存到本地
        [TTLoginSingle saveGoldStatus];
        
    });
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"实时金价";
    
    [self getNoteHintStatus];
    
    if (self.dataArray.count == 0) {
        [self getMarketListData];
    }
    
    self.tableView.tableHeaderView = [self setupHeaderView];
    self.tableView.tableFooterView = [self setupFooterView];
    
    [self.tableView reloadData];
    
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TTMarketModel *model = self.dataArray[indexPath.row];
    TTMarketViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    cell.model = model;
    return cell;
}

- (void)getMarketListData
{
    [[LLNetworkManagerTool sharedManager] postUrlString:goldPrice_api parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *marketDic;
        TTLoginSingle *single = [TTLoginSingle sharedSingle];
        if (single.isLogin) {
            marketDic = [TTLoginSingle sharedSingle].marketDic;
        } else {
            marketDic = [TTLoginSingle sharedSingle].unLoginMarketDic;
        }
        [self.dataArray removeAllObjects];
        NSMutableArray *arr = [NSMutableArray array];
        for (NSDictionary *dic in responseObject[@"PriceList"]) {
            TTMarketModel *model = [TTMarketModel modelWithJSON:dic];
            model.isOpen = [marketDic[model.Code] boolValue];
            if (model.isOpen) {
                [arr addObject:model];
            }
            [self.dataArray addObject:model];
        }
        
        [self.tableView reloadData];
        
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        
        
        
    } showLoadingInView:self.tableView];
}

// 短信提醒的switch
- (void)clickSwitchAction:(UISwitch *)sender
{
    @weakify(self)
    [[LLNetworkManagerTool sharedManager] postUrlString:setNoteHintStatus_api parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSLog(@"操作成功");
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        @strongify(self)
        [self.view makeToast:@"短信提醒开启失败" duration:1 position:CSToastPositionCenter];
        sender.on = !sender.on;

    } showLoadingInView:self.view];
}

// 获取短信提醒的状态
- (void)getNoteHintStatus
{
    @weakify(self)
    [[LLNetworkManagerTool sharedManager] requestMethod:GET urlString:getNoteHintStatus_api parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        @strongify(self)
        NSLog(@"--> %@", responseObject);
        self.mySwitch.on = [responseObject boolValue];
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        
    } showLoadingInView:nil];
}


- (UIView *)setupHeaderView
{
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 64)];
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(0, 0, headerView.width, 30);
    btn.backgroundColor = [UIColor whiteColor];
    [btn setTitle:@"18K金为淘托K黄、K白、玫瑰金等价格" forState:UIControlStateNormal];
    [btn setTitleColor:UIColorHex(666666) forState:UIControlStateNormal];
    [btn setImage:[UIImage imageNamed:@"zuanshi"] forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont systemFontOfSize:13];
    btn.imageEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
    btn.titleEdgeInsets = UIEdgeInsetsMake(0, 16, 0, 0);
    btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [headerView addSubview:btn];
    
    UIView *twoView = [[UIView alloc] initWithFrame:CGRectMake(0, 30, headerView.width, 34)];
    twoView.backgroundColor = kSeparatorColor;
    NSArray *titles = @[@"品种", @"销售价", @"回购价", @"高/低", @"首页展示"];
    CGFloat w = SCREEN_WIDTH / titles.count;
    for (int i = 0; i < titles.count; i++) {
        CGFloat x = w * i;
        UILabel *label = [UILabel labelTextCenterWithTitle:titles[i] color:kMainColor fontSize:14];
        label.frame = CGRectMake(x, 0, w, twoView.height);
        if (i == titles.count - 1) {
            label.textColor = UIColorHex(333333);
        }
        [twoView addSubview:label];
    }
    [headerView addSubview:twoView];
    
    return headerView;
}

- (UIView *)setupFooterView
{
    if ([TTLoginSingle sharedSingle].isLogin) {
        
        UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 60)];
        footerView.backgroundColor = [UIColor whiteColor];
        [LLLineUtilies addLineInView:footerView startPoint:CGPointMake(0, 0) endPoint:CGPointMake(footerView.width, 0) lineColor:kSeparatorColor lineWidth:10];
        UILabel *label = [UILabel labelWithTitle:@"每日短信通知" color:UIColorHex(666666) fontSize:15];
        label.frame = CGRectMake(10, 10, 120, 50);
        [footerView addSubview:label];
        
        UISwitch *sw = [[UISwitch alloc] init];
        sw.transform = CGAffineTransformMakeScale(0.75, 0.75);
        sw.onTintColor = kMainColor;
        sw.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
        [sw addTarget:self action:@selector(clickSwitchAction:) forControlEvents:UIControlEventValueChanged];
        [footerView addSubview:sw];
        self.mySwitch = sw;
        [sw mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(footerView).mas_offset(-10);
            make.centerY.equalTo(label);
        }];
        
        return footerView;
        
    } else {
        return [UIView new];
    }
}

- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.emptyImageName = @"nodata";
        _tableView.emptyTitel = @"暂无数据";
        _tableView.rowHeight = 60;
        _tableView.backgroundColor = kSeparatorColor;
        _tableView.separatorColor = kSeparatorColor;
        _tableView.separatorInset = UIEdgeInsetsMake(0, 10, 0, 10);
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([TTMarketViewCell class]) bundle:nil] forCellReuseIdentifier:cellID];
        [self.view addSubview:_tableView];
        
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) { make.top.mas_equalTo(self.mas_topLayoutGuideBottom);
            make.left.right.equalTo(self.view);
            make.bottom.equalTo(self.mas_bottomLayoutGuideBottom);
        }];
    }
    return _tableView;
}

- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

@end
